/**
 * @Project : ProgrammingExercises
 * @Package : Leetcode
 * @File : Q0876.java
 * @Author : WangRuoyu
 * @Date 2022/12/27 10:26
 */

package leetcode;

import util.ListNode;

public class Q0876 {
    public ListNode middleNode(ListNode head) {
        if (head == null) {
            return head;
        } else if (head.next == null) {
            return head;
        } else if (head.next.next == null) {
            return head.next;
        }
        ListNode p = head;
        ListNode s = head;

        while (s != null) {
            if (s.next == null) {
                return p;
            } else if (s.next.next == null) {
                return p.next;
            } else {
                p = p.next;
                s = s.next.next;
            }
        }

        return null;
    }

    public static void main(String[] args) {
        Q0876 sl = new Q0876();
        ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
        System.out.println(sl.middleNode(head).val);
    }
}
